var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new(static.Server)('./public', { cache: 0 });

var server = require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    });
});

server.listen(8080);

var nowjs = require("now");
var simplegeo = require('simplegeo-client');
var simplegeoSecret = "fW53PdQSmjjYnMKYmk5XLGXZhskNn8dH";
var sg_jsonp_token = "wt3NYwTFUaUVdzn2QUcKmnsTL8crFd9w";
var oath_key = "ZAzSvQLrft4BaZXqc6L2ZgkWgnfnv53s";
var sgClient = new simplegeo.SimpleGeo(oath_key,simplegeoSecret);


var everyone = nowjs.initialize(server);
var moderator;

everyone.connected(function(){
  	console.log("Joined: " + this.user.clientId);
	if (moderator == null) {
		console.log("setting moderator to: " + this.user.clientId);
		moderator = this.user.clientId;
		everyone.now.isModerator();
	} else {
		console.log("Moderator is already set to " + moderator);
		everyone.now.isModerator();
	}
});

everyone.disconnected(function(){
  	console.log("Left: " + this.now.name);
	everyone.now.distributeMember();
	
	if (this.user.clientId == moderator) {
		console.log("Moderator just left, choose a new one");
		chooseNewModerator();
	}
});

everyone.now.distributeMessage = function(message){
	everyone.now.receiveMessage(this.now.name, message);
};

everyone.now.isModerator = function() {
	var moderatorName = "";
	nowjs.getClient(moderator, function() {
		moderatorName = this.now.name;
		console.log("Moderator name: " + moderatorName + " with id: " + moderator);
	});
	if (this.user.clientId == moderator) {
		console.log("Setting moderator for " + this.user.clientId + " to true");
		this.now.receiveModerator(true, moderator, moderatorName);
	} else {
		console.log("Setting moderator for " + this.user.clientId + " to false");
		this.now.receiveModerator(false, moderator, moderatorName);
	}
};

chooseNewModerator = function() {
	var numUsers;
	console.log("Choosing new moderator");
	
	everyone.count(function (cnt) {
		numUsers = cnt;
		if (numUsers != 0) {
			console.log("Number of currently logged in users: " + numUsers);
			var rand = Math.floor(Math.random()*numUsers);
			console.log("Random number for new moderator: " + rand);

			everyone.getUsers(function (users) {
			  	for (var user in users) console.log("User: " + user);
				moderator = users[rand];
				console.log("New moderator: " + moderator);
				everyone.now.isModerator();
			});
		} else {
			console.log("There are no more members - setting moderator to null");
			moderator = null;
		}
	});
};

//Helper to inform client of all connected clients
everyone.now.distributeAllMembers = function() {
	console.log("Distributing member list");
	var members = [];
	var moderatorName;

	everyone.getUsers(function (users) {
	  	for (var i = 0; i < users.length; i++) {
			var theUser = users[i]
			console.log("user: " + theUser);
			nowjs.getClient(theUser, function() {
				var userName = this.now.name;
				console.log("Member: " + userName);
				if (theUser == moderator) {
					moderatorName = userName;
					console.log("moderator name: " + moderatorName);
				}
				members[members.length] = userName;
			});
		}
		
		everyone.now.receiveMemberList(members, moderatorName);
	});
};

everyone.now.distributeAllLocations = function() {
	console.log("Getting all locations");
	everyone.now.distributeLocation();
};

//Helper to inform client of all connected clients locations
everyone.now.distributeLocation = function() {
	console.log("Member " + this.user.clientId);
	everyone.now.receiveMemberLocations(this.user.clientId, this.now.name, this.now.lat, this.now.lng);
};

everyone.now.distributeSearch = function(middleLat, middleLng, query, category) {
	console.log("Search initiatied for " + category);
	
	sgClient.getNearbyPlaces(simplegeo.SimpleGeo.LATLNG, [middleLat, middleLng], {category: category, radius: 10}, function(err, data) {
	    if (err) {
	        console.error(err);
	    } else {
	        console.log(JSON.stringify(data));
			everyone.now.receiveSearch(moderator, category, data);
	    }
	});
};

